home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 12150 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.0 KB  |  78 lines

  1. Path: hubcap.clemson.edu!hubcap!mjs
  2. From: mjs@hubcap.clemson.edu (M. J. Saltzman)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Settle a bet please
  5. Date: 29 Mar 96 14:59:28 GMT
  6. Organization: Clemson University
  7. Message-ID: <mjs.828111568@hubcap>
  8. References: <4jfopb$o9n@news1.sympatico.ca> <KASPER.96Mar29073654@acm.org>
  9. NNTP-Posting-Host: hubcap.clemson.edu
  10. X-Newsreader: NN version 6.5.0 #1
  11.  
  12. kasperowski@acm.org writes:
  13.  
  14. >In article <4jfopb$o9n@news1.sympatico.ca> Gisele Swinson <gisele.swinson@sympatico.ca> writes:
  15.  
  16. > | In C language, how do they calculate the length of an array.
  17. > | 
  18. > | example
  19. > | 
  20. > | To declare a string "My Name"
  21. > | 
  22. > | is it char name[7] = "My Name"
  23. > | or
  24. > | is it chat Name[8] = "My Name"
  25.  
  26. > char Name[8] = "My Name";
  27.  
  28. >is correct.  There's a \0 at the end of "My Name".
  29.  
  30. > char Name[] = "My Name";
  31.  
  32. >is better; the compiler does the counting for you.
  33.  
  34. Actually, all three are correct, they just mean different things.  First,
  35.  
  36.     char name[] = "My name";
  37.  
  38. and 
  39.  
  40.     char name[8] = "My name";
  41.  
  42. do mean the same thing: reserve 8 chars and initialize them to contain
  43.  
  44.     {'M', 'y', ' ', 'n', 'a', 'm', 'e', '\0'}.  
  45.  
  46. This means that name[] can be treated as a "C string" (i.e., a
  47. null-terminated string) and used with the C string and i/o library
  48. routines that understand about null-terminated strings.
  49.  
  50. But
  51.  
  52.     char name[7] = "My name";
  53.  
  54. reserves 7 chars, and initializes them to contain
  55.  
  56.     {'M', 'y', ' ', 'n', 'a', 'm', 'e'}.
  57.  
  58. This is perfectly legal C, but the resulting array of characters is
  59. not a "C string" and can't be used with the C library functions that
  60. understand null-terminated strings.  It can still be used with the mem*
  61. functions, which require that the length of the arguments be passed
  62. as an argument.
  63.  
  64. Caveats:  
  65.     (1) This may be different in C++.  If you want to know about C++,
  66.     post in comp.lang.c++.
  67.  
  68.     (2) Of course, we've said nothing about 
  69.  
  70.         char *name = "My name";
  71.  
  72.     If you want to know about that, see the FAQ.
  73.  
  74. -- 
  75.         Matthew Saltzman
  76.         Clemson University Math Sciences
  77.         mjs@clemson.edu
  78.